package org.standard.base.action;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import org.standard.commons.struts2.BaseAction;
import org.standard.commons.utils.FileUtils;

public class DataBaseManager extends BaseAction {
	private static String MYSQL_PATH =File.separator+"upload"+File.separator+"mysql"+File.separator;
	private static String File_PATH =File.separator+"upload";
	private static String TEMP_PATH =File.separator+"upload"+File.separator+"temp"+File.separator;
	private static String TEMP1_PATH =File.separator+"upload"+File.separator+"temp1"+File.separator;
	private String inputPath;
	private String fileType;
	private String fileName;
	private String uploadName;
	private String upLoadFile;
	
	public InputStream getTargetFile(){
		File file = new File(inputPath);
		try {
			return new FileInputStream(file);
		} catch (FileNotFoundException e) {
			return ServletActionContext.getServletContext().getResourceAsStream(inputPath);
		}
	}
	
	
	public String index(){
		
		return "index";
	}
	
	 public String mySqlDownload(){
		 File file = dataBackup();
	    	
	    	if(file != null && file.length() != 0){
	    		
	    		inputPath =  file.getPath();
	    		
	    		fileType = inputPath.substring(inputPath.lastIndexOf(".") + 1,inputPath.length());
	    		fileName = "hros."+fileType;
	    		try {
	    			fileName = new String(fileName.getBytes(),"ISO8859-1");
	    		} catch (UnsupportedEncodingException e) {
	    			// TODO Auto-generated catch block
	    			e.printStackTrace();
	    		}
	    		return "download";
	    	}else{
	    		info = "数据库导出失败!";
	    		return "index";
	    	}
	    }
	 
	 public String fileDownload(){
		 File file = fileBackup();
	    	
	    	if(file != null && file.length() != 0){
	    		
	    		inputPath =  file.getPath();
	    		
	    		fileType = inputPath.substring(inputPath.lastIndexOf(".") + 1,inputPath.length());
	    		fileName = "hros."+fileType;
	    		try {
	    			fileName = new String(fileName.getBytes(),"ISO8859-1");
	    		} catch (UnsupportedEncodingException e) {
	    			// TODO Auto-generated catch block
	    			e.printStackTrace();
	    		}
	    		return "download";
	    	}else{
	    		info="文件备份失败!";
	    		return "index";
	    	}
	 }
	
	 public String allFileDownload(){
		 File file = backUpAll();
		 
		 if(file != null && file.length() != 0){
			 
			 inputPath =  file.getPath();
			 
			 fileType = inputPath.substring(inputPath.lastIndexOf(".") + 1,inputPath.length());
			 fileName = "hrosAll."+fileType;
			 try {
				 fileName = new String(fileName.getBytes(),"ISO8859-1");
			 } catch (UnsupportedEncodingException e) {
				 // TODO Auto-generated catch block
				 e.printStackTrace();
			 }
			 return "download";
		 }else{
			 info="备份失败!";
			 return "index";
		 }
	 }
	 
	 
	 
	 public File backUpAll(){
		 FileUtils ft = new FileUtils();
		 
		 ArrayList<File> files = new ArrayList<File>();
		 	files.add(dataBackup());
		 	files.add(fileBackup());
			
		 	File tempFile = new File(request.getSession().getServletContext().getRealPath("")+TEMP1_PATH);
			 File f1 = null;
			 if(!tempFile.exists()){
				// tempFile.mkdirs();
				 tempFile.mkdir();
				 try {
					f1 = tempFile.createTempFile("temp1", ".zip",tempFile);
					
					boolean a = ft.fileZip(files, f1.getPath());
					
					if(a == true){
						info = "文件备份失败!";
					}else{
						info = "文件备份成功!";
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			 }else{
				 if(tempFile.isDirectory()){
		    			File[] fileListi = tempFile.listFiles();
		    			if(fileListi.length>0){
		    				for(int i=0;i<fileListi.length;i++){
		    					fileListi[i].delete();
		    				}
		    			}
	 				}
				 
				 try {
						f1 = tempFile.createTempFile("temp", ".zip",tempFile);
						
						boolean a = ft.fileZip(files, f1.getPath());
						
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			 }
			 return f1;
	 }
	 
	 
	 
	 
	 /**
	     * 备份检验一个sql文件是否可以做导入文件用的一个判断方法：把该sql文件分别用记事本和ultra
	     * edit打开，如果看到的中文均正常没有乱码，则可以用来做导入的源文件（不管sql文件的编码格式如何，也不管db的编码格式如何）
	     */
	    private File dataBackup() {
	    	File file = null;
	    	try {
	    		   Runtime rt = Runtime.getRuntime();
		            
		            //linux下调用 mysql 的 cmd:
		           Process child = rt.exec("/usr/local/mail/mysql/bin/mysqldump -u hros --password=hros --opt hros ");// 设置导出编码为utf8。这里必须是utf8
		           
		            // 把进程执行中的控制台输出信息写入.sql文件，即生成了备份文件。注：如果不对控制台信息进行读出，则会导致进程堵塞无法运行
		            InputStream in = child.getInputStream();// 控制台的输出信息作为输入流
		                       
		            //InputStreamReader xx = ;// 设置输出流编码为utf8。这里必须是utf8，否则从流中读入的是乱码
		           
		            String inStr;
		            StringBuffer sb = new StringBuffer("");
		            String outStr;
		            // 组合控制台输出信息字符串
		            BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf8"));
		            // 要用来做导入用的sql目标文件：
		            String sqlPath =  request.getSession().getServletContext().getRealPath("")+MYSQL_PATH;
		           
		            File file1=new File(sqlPath);
		    		
		            
		            if(!file1.exists()){
		    			file1.mkdir();
		    		}else{
		    			if(file1.isDirectory()){
			    			File[] fileList = file1.listFiles();
			    			if(fileList.length>0){
			    				for(int i=0;i<fileList.length;i++){
			    					fileList[i].delete();
			    				}
			    			}
		    			}
		    		}
		            
		    		Date date = new Date();
		    		file = new File(sqlPath,date.getTime()+".sql");
		    		
		    		if(file.exists()){
		    			file.delete();
		    			file.createNewFile();
		    		}else{
		    			file.createNewFile();
		    		}
		    		
		            FileOutputStream fout = new FileOutputStream(file);
		            OutputStreamWriter writer = new OutputStreamWriter(fout, "utf8");
		            
		            while (br.readLine() != null) {
		            	writer.write(br.readLine()+ "\r\n");
		            }
		            // 注：这里如果用缓冲方式写入文件的话，会导致中文乱码，用flush()方法则可以避免
		            writer.flush();
		            // 别忘记关闭输入输出流
		            writer.close();
		            fout.close();
		            br.close();
		            in.close();
		            
	        } catch (Exception e) {
	        	
	        	Runtime rt = Runtime.getRuntime();

		            // 调用 mysql 的 cmd:
		           Process child;
				try {
					child = rt.exec("mysqldump -u hros --password=hros --opt hros ");
					
					
					  // 把进程执行中的控制台输出信息写入.sql文件，即生成了备份文件。注：如果不对控制台信息进行读出，则会导致进程堵塞无法运行
		            InputStream in = child.getInputStream();// 控制台的输出信息作为输入流
		                       
		            //InputStreamReader xx = ;// 设置输出流编码为utf8。这里必须是utf8，否则从流中读入的是乱码
		           
		            String inStr;
		            StringBuffer sb = new StringBuffer("");
		            String outStr;
		            // 组合控制台输出信息字符串
		            BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf8"));
		            // 要用来做导入用的sql目标文件：
		            String sqlPath =  request.getSession().getServletContext().getRealPath("")+MYSQL_PATH;
		           
		            File file1=new File(sqlPath);
		    		
		            
		            if(!file1.exists()){
		    			file1.mkdir();
		    		}else{
		    			if(file1.isDirectory()){
			    			File[] fileList = file1.listFiles();
			    			if(fileList.length>0){
			    				for(int i=0;i<fileList.length;i++){
			    					fileList[i].delete();
			    				}
			    			}
		    			}
		    		}
		            
		    		Date date = new Date();
		    		file = new File(sqlPath,date.getTime()+".sql");
		    		
		    		if(file.exists()){
		    			file.delete();
		    			file.createNewFile();
		    		}else{
		    			file.createNewFile();
		    		}
		    		
		            FileOutputStream fout = new FileOutputStream(file);
		            OutputStreamWriter writer = new OutputStreamWriter(fout, "utf8");// 设置导出编码为utf8。这里必须是utf8
		            
		            while (br.readLine() != null) {
		            	writer.write(br.readLine()+ "\r\n");
		            }
		            // 注：这里如果用缓冲方式写入文件的话，会导致中文乱码，用flush()方法则可以避免
		            writer.flush();
		            // 别忘记关闭输入输出流
		            writer.close();
		            fout.close();
		            br.close();
		            in.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
	        }
	        return file;
	    }


	    
	public File fileBackup(){
		
		File tempFile = null;
		FileUtils ft = new FileUtils();
		 
		 String filePath = request.getSession().getServletContext().getRealPath("")+File_PATH;
		 File file = new File(filePath);
		 if(!file.exists()){
			 file.mkdir();
		}
		 ArrayList<File> files = new ArrayList<File>();
		 ArrayList<File> files1 = new ArrayList<File>();
		 File[] fileList = file.listFiles();
		
		 for(int i=0;i<fileList.length;i++){
			 
			 files.add(fileList[i]);
		 }
		 
		 files1 = ft.getAllFile(files);
		 
		tempFile = new File(request.getSession().getServletContext().getRealPath("")+TEMP_PATH);
		 File f1 = null;
		 if(!tempFile.exists()){
			// tempFile.mkdirs();
			 tempFile.mkdir();
			 try {
				f1 = tempFile.createTempFile("file", ".zip",tempFile);
				
				boolean a = ft.fileZip(files1, f1.getPath());
				
				if(a == true){
					info = "文件备份失败!";
				}else{
					info = "文件备份成功!";
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 }else{
			 if(tempFile.isDirectory()){
	    			File[] fileListi = tempFile.listFiles();
	    			if(fileListi.length>0){
	    				for(int i=0;i<fileListi.length;i++){
	    					fileListi[i].delete();
	    				}
	    			}
 				}
			 
			 try {
					f1 = tempFile.createTempFile("temp", ".zip",tempFile);
					
					boolean a = ft.fileZip(files1, f1.getPath());
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		 }
		 return f1;
	}

//	public String getInputPath() {
//		return inputPath;
//	}



	public void setInputPath(String inputPath) {
		this.inputPath = inputPath;
	}



	public String getFileType() {
		return fileType;
	}



	public void setFileType(String fileType) {
		this.fileType = fileType;
	}



	public String getFileName() {
		return fileName;
	}



	public void setFileName(String fileName) {
		this.fileName = fileName;
	}



	public String getUploadName() {
		return uploadName;
	}



	public void setUploadName(String uploadName) {
		this.uploadName = uploadName;
	}


	public String getUpLoadFile() {
		return upLoadFile;
	}


	public void setUpLoadFile(String upLoadFile) {
		this.upLoadFile = upLoadFile;
	}
	    
}
